package org.example.controller;

import org.example.service1.api.dubboservice1api;
import org.example.service2.api.dubboservice2api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@RestController
public class RestConsumerController {
    //从配置中心获取common.name
    @Value("${common.name}")
    private String commonName;
    @Autowired
    private ConfigurableApplicationContext context;
    @GetMapping("/config")
    public String config() {
        return context.getEnvironment().getProperty("common.name");
    }
    //扩展配置
    @GetMapping("/config1")
    public String config1() {
        String name=context.
                getEnvironment().getProperty("common.name");
        String address=context.
                getEnvironment().getProperty("common.addr");
        String age=context.
                getEnvironment().getProperty("common.age");
        return "name:"+name + "address:"+address+"age:"+age;
    }
    //dubbo服务调用
    @org.apache.dubbo.config.annotation.Reference
    private dubboservice2api service2Api;
    @org.apache.dubbo.config.annotation.Reference
    private dubboservice1api service1Api;
    @GetMapping("/service3")
    public String service3() {
        //远程调用service1
        String providerResult = service1Api.dubboService1();
        return "consumer dubbo invoke | " + providerResult;
    }
    @GetMapping("/service2")
    public String service2() {
        //远程调用service2
        String providerResult = service2Api.dubboService2();
        return "consumer dubbo invoke | " + providerResult;
    }
    //nacos服务中心
    @Autowired
    LoadBalancerClient loadBalancer;//负载均衡客户端，可以从服务器中选择一个合适的实例返回
    @GetMapping("/service")
    public String service() {
        ServiceInstance choose = loadBalancer.choose("nacos-restful-producer");
        URI uri = choose.getUri();//获取请求的uri
        System.out.println(uri);
        //调用服务提供者中的内容: http://localhost:8888/show
        RestTemplate restTemplate = new RestTemplate();
        //String result = restTemplate.getForObject("http://localhost:8081/show", String.class);
        String result = restTemplate.getForObject(uri+"/show", String.class);
        return "consumer invoke |"+result;
    }

}
